from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.views import View
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth import authenticate
from .serializers import UserSerializer
from backend.third_party.jwt_tool import toolJWT
from django.db import IntegrityError
from .models import User
from rest_framework.parsers import MultiPartParser, FormParser
import re
from django.utils import timezone


from backend.utils.redis_client import redis_client

from backend.utils.captcha import ImageCaptcha
from backend.third_party.sms_service import sms_service

image_captcha = ImageCaptcha()
# Create your views here.
class ImageCodeView(APIView):
    """获取图片验证码"""
    def get(self, request):
        uuid = request.GET.get('uuid')
        print(f"获取到的UUID: {uuid}")
        if not uuid:
            return Response({'code': 400, 'msg': '缺少uuid参数'}, status=status.HTTP_400_BAD_REQUEST)

        # 生成验证码图片和文本
        image_buf, code = image_captcha.generate_captcha()
        print(f"生成的验证码: {code}")

        # 将验证码文本存入Redis，有效期5分钟
        redis_client.set(f'image_code:{uuid}', code.lower(), 300)

        # 返回图片流
        return HttpResponse(image_buf.getvalue(), content_type='image/jpeg')
class LoginView(APIView):
    """
    用户名+密码登录视图，校验成功返回JWT和用户信息
    """
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        if not username or not password:
            return Response({'msg': '用户名和密码不能为空'}, status=status.HTTP_400_BAD_REQUEST)
        user = authenticate(username=username, password=password)
        if user is not None and user.status == 1:
            # 生成JWT和刷新token
            user_data = {
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'phone': user.phone,
                'avatar': request.build_absolute_uri(user.avatar.url) if user.avatar else '',
            }
            token = toolJWT.getjwt(user_data)
            retoken = toolJWT.get_refresh_token(user_data)
            return Response({
                'msg': '登录成功',
                'token': token,
                'retoken': retoken,
                'user': UserSerializer(user, context={'request': request}).data
            }, status=status.HTTP_200_OK)
        else:
            return Response({'msg': '用户名或密码错误，或账号被禁用'}, status=status.HTTP_401_UNAUTHORIZED)

class RegisterView(APIView):
    """
    用户注册视图，支持用户名、密码、手机号、邮箱、头像注册，返回JWT和用户信息。
    支持图片文件上传（multipart/form-data）。
    """
    parser_classes = [MultiPartParser, FormParser]

    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        phone = request.data.get('phone')
        email = request.data.get('email')
        avatar = request.FILES.get('avatar')  # 获取上传的图片文件
        if not username or not password:
            return Response({'msg': '用户名和密码不能为空'}, status=status.HTTP_400_BAD_REQUEST)
        try:
            user = User.objects.create_user(
                username=username,
                password=password,
                phone=phone,
                email=email,
                avatar=avatar
            )
        except IntegrityError:
            return Response({'msg': '用户名、手机号或邮箱已存在'}, status=status.HTTP_400_BAD_REQUEST)
        user_data = {
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'phone': user.phone,
            'avatar': request.build_absolute_uri(user.avatar.url) if user.avatar else '',
        }
        token = toolJWT.getjwt(user_data)
        retoken = toolJWT.get_refresh_token(user_data)
        return Response({
            'msg': '注册成功',
            'token': token,
            'retoken': retoken,
            'user': UserSerializer(user, context={'request': request}).data
        }, status=status.HTTP_201_CREATED)

class SendSmsCodeView(APIView):
    """
    发送短信验证码视图
    """
    def post(self, request):
        phone = request.data.get('phone')
        image_code = request.data.get('image_code', '').lower()
        uuid = request.data.get('uuid')

        print(f"接收到的参数: phone={phone}, image_code={image_code}, uuid={uuid}")

        # 验证手机号格式
        if not re.match(r'^1[3-9]\d{9}$', phone):
            return Response({'code': 400, 'msg': '手机号格式不正确'}, status=status.HTTP_400_BAD_REQUEST)

        # 验证图片验证码
        if not uuid or not image_code:
            return Response({'code': 400, 'msg': '请输入图片验证码'}, status=status.HTTP_400_BAD_REQUEST)

        # 从Redis获取图片验证码
        stored_code = redis_client.get(f'image_code:{uuid}')
        print(f"Redis中存储的验证码: {stored_code}, 用户输入的验证码: {image_code}")
        
        if not stored_code or stored_code != image_code:
            return Response({'code': 400, 'msg': '图片验证码错误'}, status=status.HTTP_400_BAD_REQUEST)

        # 检查是否在1分钟内发送过短信
        if redis_client.exists(f'sms_sent:{phone}'):
            return Response({'code': 400, 'msg': '请1分钟后再试'}, status=status.HTTP_400_BAD_REQUEST)

        # 发送验证码
        result = sms_service.create_and_send_code(phone)
        
        if result['success']:
            # 记录发送时间，用于限制发送频率
            redis_client.set(f'sms_sent:{phone}', '1', 60)
            # 删除图片验证码
            redis_client.delete(f'image_code:{uuid}')
            return Response({'msg': '短信验证码发送成功'}, status=status.HTTP_200_OK)
        else:
            return Response({'code': 400, 'msg': result['message']}, status=status.HTTP_400_BAD_REQUEST)


class SmsLoginView(APIView):
    """
    短信验证码登录视图
    """
    def post(self, request):
        phone = request.data.get('phone')
        code = request.data.get('code')

        if not phone or not code:
            return Response({'msg': '手机号和验证码不能为空'}, status=status.HTTP_400_BAD_REQUEST)

        # 验证手机号格式
        phone_pattern = re.compile(r'^1[3-9]\d{9}$')
        if not phone_pattern.match(phone):
            return Response({'msg': '手机号格式不正确'}, status=status.HTTP_400_BAD_REQUEST)

        # 验证验证码
        verify_result = sms_service.verify_code(phone, code)

        if not verify_result['success']:
            return Response({'msg': verify_result['message']}, status=status.HTTP_400_BAD_REQUEST)

        # 查找用户（不自动创建）
        try:
            user = User.objects.get(phone=phone)
            if user.status != 1:
                return Response({'msg': '账号已被禁用'}, status=status.HTTP_401_UNAUTHORIZED)
        except User.DoesNotExist:
            # 如果用户不存在，提示用户去注册
            return Response({
                'msg': '该手机号未注册，请先注册账号',
                'code': 'USER_NOT_EXISTS'
            }, status=status.HTTP_404_NOT_FOUND)

        # 更新最后登录时间
        user.last_login_time = timezone.now()
        user.save()

        # 生成JWT和刷新token
        user_data = {
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'phone': user.phone,
            'avatar': request.build_absolute_uri(user.avatar.url) if user.avatar else '',
        }
        token = toolJWT.getjwt(user_data)
        retoken = toolJWT.get_refresh_token(user_data)

        return Response({
            'msg': '登录成功',
            'token': token,
            'retoken': retoken,
            'user': UserSerializer(user, context={'request': request}).data
        }, status=status.HTTP_200_OK)

class RefreshTokenView(APIView):
    """
    刷新token视图
    """
    def post(self, request):
        refresh_token = request.data.get('refresh_token')
        if not refresh_token:
            return Response({'msg': '刷新token不能为空'}, status=status.HTTP_400_BAD_REQUEST)
        
        result = toolJWT.refresh_access_token(refresh_token)
        if result['success']:
            return Response({
                'msg': 'token刷新成功',
                'token': result['token']
            }, status=status.HTTP_200_OK)
        else:
            return Response({'msg': result['error']}, status=status.HTTP_401_UNAUTHORIZED)

class TestView(APIView):
    """
    测试视图
    """
    def get(self, request):
        return Response({'msg': 'API正常工作'}, status=status.HTTP_200_OK)
    
    def post(self, request):
        return Response({'msg': 'POST请求正常工作', 'data': request.data}, status=status.HTTP_200_OK)

class SimpleLoginView(APIView):
    """
    简单登录测试视图
    """
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        
        print(f"收到登录请求: username={username}, password={password}")
        
        if not username or not password:
            return Response({'msg': '用户名和密码不能为空'}, status=status.HTTP_400_BAD_REQUEST)
        
        # 简单的测试逻辑
        if username == 'test' and password == 'test':
            return Response({
                'msg': '登录成功',
                'token': 'test_token_123',
                'user': {'username': username}
            }, status=status.HTTP_200_OK)
        else:
            return Response({'msg': '用户名或密码错误'}, status=status.HTTP_401_UNAUTHORIZED)

class DebugLoginView(APIView):
    """
    调试登录视图 - 完全不依赖认证
    """
    authentication_classes = []  # 禁用认证
    permission_classes = []      # 禁用权限
    
    def post(self, request):
        print(f"收到POST请求: {request.data}")
        print(f"请求头: {request.headers}")
        
        username = request.data.get('username')
        password = request.data.get('password')
        
        print(f"用户名: {username}, 密码: {password}")
        
        # 简单的测试逻辑
        if username == 'test' and password == 'test':
            return Response({
                'msg': '调试登录成功',
                'token': 'debug_token_123',
                'user': {'username': username}
            }, status=status.HTTP_200_OK)
        else:
            return Response({
                'msg': '用户名或密码错误',
                'received_username': username,
                'received_password': password
            }, status=status.HTTP_401_UNAUTHORIZED)
